<template>
  <el-dialog :title="'导入进度'" :visible.sync="visible" :close-on-click-modal="closeOnClickModal" @open="_handleDialogOpen" @close="_cancel">
    <el-progress :text-inside="true" :stroke-width="20" :percentage="percentage"/>
    <div v-if="progressInfo" class="info" v-html="progressInfo"/>
    <div class="msg-error">
      <ul class="msg-list">
        <li v-for="(item, index) in resultList" :key="index">第{{ item.row }}行<template v-if="item.col">、第{{ item.col }}列</template> 导入失败：{{ item.desc }}</li>
      </ul>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="_loading" size="small" @click="_interrupt(contextData.key)">中止</el-button>
      <el-button size="small" type="primary" @click="_cancel">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>

import dataApi from '@/api/common/data'

export default {

  props: {
    closeOnClickModal: {
      type: Boolean,
      default: false
    },

    loading: {
      type: Boolean,
      default: false
    },

    resultDisplayType: {
      type: String,
      default: 'sync'
    }
  },

  data() {
    return {
      visible: false,
      intervalId: null,
      invalidCount: 0,
      resultList: [],
      contextData: {},
      progressInfo: '数据处理中，请稍等 ...',
      percentage: 0
    }
  },

  computed: {
    '_loading': {
      get() {
        return this.loading
      },

      set(value) {
        this.$emit('update:loading', value)
      }
    }
  },

  deactivated() {
    if (this.contextData.key) {
      this._interrupt(this.contextData.key, false)
    }
  },

  beforeDestroy() {
    if (this.contextData.key) {
      this._interrupt(this.contextData.key, false)
    }
  },

  methods: {
    _reset() {
      this.intervalId = null
      this.invalidCount = 0
      this.resultList = []
      this.contextData = {}
      this.progressInfo = '数据处理中，请稍等 ...'
      this.percentage = 0
    },

    _handleDialogOpen() {
      this.$emit('open')
    },

    _cancel() {
      this.visible = false
      this.isLoading = false
      if (this.contextData.key) {
        this._interrupt(this.contextData.key, false)
      }
      this._stopProgress(this.intervalId)
      this._reset()
      this.$emit('cancel', Object.assign({}, this.contextData))
    },

    _ok() {
      this.$emit('ok', Object.assign({}, this.contextData), false)
    },

    _stopProgress(id) {
      const intervalId = id || this.intervalId
      if (!intervalId) {
        return
      }
      clearInterval(intervalId)
      this.intervalId = null
    },

    _startProgress(key) {
      if (!key) {
        return
      }
      this.contextData.key = key
      this.intervalId = setInterval(() => {
        dataApi.getImportProgress({
          key: key
        }).then(resp => {
          const data = resp.data
          this.contextData.result = data
          if (data && !data.completed) {
            this.percentage = Math.round(data.processedCount * 10000 / (data.totalCount || 1)) / 100
            this.progressInfo = `数据总数：${data.totalCount}，已处理数量：${data.processedCount}`
          } else if (data) {
            if (!data.isInterrupted) {
              this.percentage = 100
            }
            if (!data.resultList || !data.resultList[0]) {
              this.progressInfo = `<strong>数据导入成功</strong> （共处理数据数量：${data.totalCount}）`
            } else {
              this.progressInfo = `<font color="red"><strong>数据导入失败</strong></font> （共处理数据数量：${data.totalCount}）`
            }
            this._stopProgress()
          } else {
            this.invalidCount = this.invalidCount + 1
            if (this.invalidCount > 60) {
              this._stopProgress()
            }
          }

          if (data && this.resultDisplayType === 'sync') {
            this.resultList = data.resultList || []
          } else if (data && this.resultDisplayType === 'end' && data.computed) {
            this.resultList = data.resultList || []
          }
        }).catch(resp => {
          this._stopProgress()
          this.$message.error(resp.message || '出错了')
        })
      }, 1000)
    },

    _interrupt(key, isShowErrorMessage) {
      if (!key) {
        return
      }

      dataApi.interruptImport({
        key: key
      }).then(resp => {
        this.contextData.key = null
        this._stopProgress()
        this.$message.success(resp.message)
      }).catch(resp => {
        if (isShowErrorMessage === false) {
          return
        }
        this.$message.error(resp.message)
      })
    },

    show(params) {
      this.visible = true
      if (params) {
        this._startProgress(params.key || params)
      }
    },

    close() {
      this._cancel()
    }
  }
}
</script>

<style lang="scss" scoped>
.info {
  padding: 8px 0;
  color: #0dbc79;
}
.msg-error {
  margin-top: 5px;
  max-height: 400px;
  overflow-y: auto;
}
</style>
